package com.swt;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SwtImage {
	static Display display = new Display();
	static Shell shell = new Shell(display);
	
	public static void showme(){
		new SwtImage().init();
	}
	
	public void init(){
		shell.setSize(500, 500);
		shell.setText("image test window");
		Image image = getImage();
		
		shell.setBackgroundImage(image);								
		
		shell.open();
		while (!shell.isDisposed()) {
			if (display.readAndDispatch()) {
				display.sleep();
			}
		}
		display.dispose();
	}
	
	public Image getImage(){
		Image image = null;
		try {
			DBTool dbtool = DBTool.newInstance();
			Connection conn = dbtool.getConnection();
			String sql = "select r_name, r_btformat, r_image from t_b_resources where r_type <> ?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, 0);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				//方式一
//				InputStream is = rs.getBinaryStream(1);
//				image = new Image(display, is);
				//方式二
//				ImageLoader il = new ImageLoader();
//				ImageData[] imageDatas = il.load(is);
//				image = new Image(null, imageDatas[0]);
				//保存至本地
				byte[] b = new byte[512];
				int len = 0;
				//getBinaryStream()比较特殊
				//在获取任何其他列的值之前必须读取返回流中的所有数据
				//下一次调用获取方法将隐式关闭该流
				//也就是is或被自动关闭,也就是每次从数据库读取二进制数据时,都必须先读取完成,再获取其他字段值
				String filename = rs.getString(1);
				InputStream is = rs.getBinaryStream(2);
				System.out.println(filename);
				File file = new File(filename);
				OutputStream os = new FileOutputStream(file);
				while((len = is.read(b, 0, b.length))>0){
					os.write(b,0,len);
				}
				os.close();
				is.close();
			}
			dbtool.closeResultSet(rs);
			dbtool.closePstmt(pstmt);
			dbtool.closeConn(conn);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}
	
	public static void main(String[] args) {
		SwtImage.showme();
	}
}
